package com.ciaojian.core.enums.base;

import com.baomidou.mybatisplus.core.enums.IEnum;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.ciaojian.core.util.LogUtil;
import com.fasterxml.jackson.annotation.JsonValue;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Objects;


/**
 * 枚举基本接口
 *
 * @author Atlakyn
 */
public interface IBaseEnum extends IEnum {
    /**
     * 获取枚举的值
     *
     * @return 枚举值
     */
    @Override
    @JsonValue
    Integer getValue();

    /**
     * 获取枚举的映射字符串
     *
     * @return 返回枚举的映射字符串
     */
    String getDescription();

    /**
     * 根据枚举值取枚举对象
     *
     * @param enumClass 枚举类型
     * @param value     枚举值
     * @param <E>       对应枚举
     * @return /
     */
    static <E extends IEnum<?>> E valueOf(Class<E> enumClass, Object value) {
        E[] es = enumClass.getEnumConstants();
        Method method;
        try {
            method = enumClass.getMethod("getValue");
            for (E e : es) {
                Object eValue;
                try {
                    method.setAccessible(true);
                    eValue = method.invoke(e);
                } catch (IllegalAccessException | InvocationTargetException e1) {
                    throw ExceptionUtils.mpe("Error: NoSuchMethod in {}.  Cause:", e, enumClass.getName());
                }
                if (value instanceof Number && eValue instanceof Number
                        && new BigDecimal(String.valueOf(value)).compareTo(new BigDecimal(String.valueOf(eValue))) == 0) {
                    return e;
                }
                if (Objects.equals(eValue, value)) {
                    return e;
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            LogUtil.writeErrorLog("枚举{}取值失败,value:{}", enumClass, value);
        }
        return null;
    }
}
